package com.dst.note.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;


import com.dst.note.R;

import java.io.File;

/**
 * Date: tgl/21 12:56
 * Description:
 * History:
 */
public class ViewToBmp {

    public static Bitmap parseBmp(Context context, File file) {
        //将布局转化成view对象
        View viewBitmap = LayoutInflater.from(context).inflate(R.layout.vocie_layout, null);
        TextView titleTv = viewBitmap.findViewById(R.id.title_tv);
        TextView sizeTv = viewBitmap.findViewById(R.id.size_tv);
        titleTv.setText(file.getName());
        sizeTv.setText(file.length() / 1024 + " KB");
        int width = DensityUtil.getScreenW(context);
        int height = DensityUtil.getScreenH(context);

        //然后View和其内部的子View都具有了实际大小，也就是完成了布局，相当与添加到了界面上。接着就可以创建位图并在上面绘制了：
        return layoutView(viewBitmap, width, height, file, context);
    }

    public static Bitmap layoutView(final View viewBitmap, int width, int height, File file, Context context) {
        // 整个View的大小 参数是左上角 和右下角的坐标
        viewBitmap.layout(0, 0, width, height);
        int measuredWidth = View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY);
        int measuredHeight = View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.AT_MOST);

        viewBitmap.measure(measuredWidth, measuredHeight);
        viewBitmap.layout(0, 0, viewBitmap.getMeasuredWidth(), viewBitmap.getMeasuredHeight());

        return convertViewToBitmap(viewBitmap);
    }

    public static Bitmap convertViewToBitmap(View view) {
        view.setDrawingCacheEnabled(true);
        view.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
        view.buildDrawingCache();

        Bitmap var2;
        try {
            // var2 = Bitmap.createBitmap(view.getDrawingCache());
            var2 = viewConversionBitmap(view);
            return var2;
        } catch (Exception var6) {
            var2 = view.getDrawingCache();
        } finally {
            view.setDrawingCacheEnabled(false);
            view.destroyDrawingCache();
        }
        var2 = viewConversionBitmap(view);
        return var2;
    }

    public static Bitmap viewConversionBitmap(View v) {
        int w = v.getWidth();
        int h = v.getHeight();
        Bitmap bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(bmp);
        v.layout(0, 0, w, h);
        v.draw(c);
        return bmp;
    }
}
